<?php

class UsersController extends AppController {

    var $name = 'Users';
    var $components = array('Session', 'Cookie', 'Thumbnail', 'Email', 'Utility');
    var $uses = array('User', 'Guest', 'Group', 'Note', 'Word', 'Language', 'UserLanguage', 'Level', 'Followship', 'Question', 'Event','Job');
    var $helpers = array('Formater', 'Avatar', 'Linker');
    

    function beforeFilter() {
        //  $this->Cookie->name = 'baker_id';
        //  $this->Cookie->time =  3600;  // or '1 hour'

        $this->Cookie->path = '/';
        //  $this->Cookie->domain = 'example.com';
        $this->Cookie->secure = false;  //i.e. only sent if using secure HTTPS
        $this->Cookie->key = 'qSI232qs*&sXOw!';
        $this->Auth->allow('login', 'do_reset_password','please_confirm','reset_password','logout', 'signup', 'password_reset', 'upload_avatar', 'not_activated', 'activate');

        parent::beforeFilter();		
		if (isset($this->user) and $this->user['User']['is_blocked']==1) {
			$this->cakeError('user_blocked');
		}
    }

    function index() {
        $this->User->recursive = 0;
        $this->set('users', $this->paginate());
    }

    function mine() {
        if (isset($this->cuid) and isset($this->cuuid)) {
            $this->redirect("/people/{$this->cuuid}/");
        } else {
            $this->redirect('/');
        }
    }

    function signup() {
        if ($this->data) {
            if ($this->data['User']['password'] == $this->Auth->password($this->data['User']['password_confirm'])) {
                $this->User->create();
                if ($this->User->save($this->data)) {
                    $code = $this->Utility->activateCode();
                    $this->User->saveField('activation_code', $code);
                    $this->User->saveField('uid', "u{$this->User->id}");
                    //  					$this->User->saveField('activate_code',String::uuid());
                    //  				if($this->Auth->login($this->data)){
                    //  				    if($this->_sendMail($this->User->id)){
                    //  				        $this->Session->setFlash('email sent');
                    //  				    }else{
                    //    	 				        $this->Session->setFlash('email not sent');
                    //  				    }
                    //
                    // 					$this->redirect("home");
                    //  				}else{
                    //                     $this->data['User']['password']='';
                    //                     $this->data['User']['password_confirm']='';
                    //                     $this->Session->setFlash('something wrong!');
                    //  				}
                    $user = $this->User->findById($this->User->id);
                    $email = $user['User']['email'];
                    $this->Email->to = "<{$email}>";
                    $this->set('code', $code);
                    $this->set('user', $user);
                    $this->Email->subject = 'activate your email';
                    $this->Email->template = 'activation';
                    $this->Email->sendAs = 'both';
                    if ($this->Email->send() && $this->Auth->login($user)) {
                        $this->redirect("home");
                    } else {
                        echo $this->Email->smtpError;
                    }
                } else {
                    $this->data['User']['password'] = '';
                    $this->data['User']['password_confirm'] = '';
                    $this->Session->setFlash('something wrong!');
                }
            }
        }
    }

    function activate() {
        if (isset($this->params['url']['code'])) {
            $code = $this->params['url']['code'];
        } else {
            $code = null;
        }
        if ($code) {
            $user = $this->User->findByActivationCode($code);
            if (!empty($user)) {
                $this->User->id = $user['User']['id'];
                $this->User->saveField('activation_code', '');
                $this->User->saveField('is_active', 1);
                if ($this->Auth->login($user)) {
                    $this->Session->setFlash('邮箱激活成功!');
                }else {
                    $this->Session->setFlash('激活码无效或已过期！请重新注册！');
                }
            } else {
                $this->Session->setFlash('激活码无效或已过期！请重新注册！');
            }
        }
    }

    function not_activated() {

    }
    function password_reset() {



        if (isset ($this->params['form']['email'])) {
            $email = $this->params['form']['email'];
            $user= $this->User->findByEmail($email);
            if ($user) {
                $this->User->id = $user['User']['id'];
                $this->User->saveField('confirm_code',String::uuid());
                $this->set('user', $this->User->findById($user['User']['id']));
                $this->Email->to = "<{$email}>";
                $this->Email->subject = "密码重置";
                $this->Email->template = "password_reset";
                $this->Email->sendAs = 'both';
                if ($this->Email->send()) {
                    $this->set('information', '请查看邮箱。');
                    $this->render("please_confirm");

                }else {
                    $this->cakeError("not_found");
                }
            }else {
                $this->set('information', '该油箱不存在。');
                $this->render('please_confirm');
            }

        }
    }
    function reset_password() {
        if (isset ($this->params['url']['confirmation'])) {
            $user = $this->User->findByConfirmCode($this->params['url']['confirmation']);
            $confirmation = $this->params['url']['confirmation'];
            $this->set('confirmation', $confirmation);
            if (!$user) {
                $this->cakeError('Access');
            }

        }


    }
    function do_reset_password() {
        if (isset ($this->params['form']['confirmation'])) {
            $user = $this->User->findByConfirmCode($this->params['form']['confirmation']);
            $confirmation = $this->params['form']['confirmation'];
            $this->set('confirmation', $confirmation);
        }
        if (!$user) {
            $this->cakeError('Access');
        }
        if (isset ($this->params['form']['new_password']) and isset($this->params['form']['password_confirm'])) {
            $password = $this->params['form']['new_password'];
            $c_password = $this->params['form']['password_confirm'];
            if ($password==$c_password) {
                $this->User->id= $user['User']['id'];
                $this->User->saveField('password',Security::hash($password, null, true));
                $user = $this->User->findById($user['User']['id']);
                if ($this->Auth->login($user)) {
                    $this->redirect("home");
                }

            }else {
                $this->redirect($this->preferer());

            }
        }else {
            $this->set('confirmation', $confirmation);
            $this->redirect("reset_password");
        }
    }
    function please_confirm() {

    }
    function login() {
        if ($this->Auth->user()) {
            if (!empty($this->data['User']['remember_me'])) {
                $cookie = array();
                $cookie['email'] = $this->data['User']['email'];
                $cookie['password'] = $this->data['User']['password'];
                $this->Cookie->write('Auth.User', $cookie, true, '+4 weeks');
                unset($this->data['User']['remember_me']);
            }
            $this->redirect($this->Auth->redirect());
        }
        if (empty($this->data)) {
            $cookie = $this->Cookie->read('Auth.User');
            if (!is_null($cookie)) {
                if ($this->Auth->login($cookie)) {
                    //  Clear auth message, just in case we use it.
                    $this->Session->delete('Message.auth');
                    $this->redirect($this->Auth->redirect());
                }
            }
        }
    }

    function logout() {
        $cookie = $this->Cookie->read('Auth.User');
        if (!is_null($cookie)) {
            $this->Cookie->delete('Auth.User');

        }
        $this->redirect($this->Auth->logout());
    }

    function home() {
        if (!isset($this->cuid)) {
            $this->cakeError('access');
        }
/*
        $following_ids = $this->Followship->find('list', array('fields' => array('Followship.following_id'), 'conditions' => array('Followship.user_id' => $this->cuid)));
        $activities = $this->paginate('Activity', array('Activity.user_id' => $following_ids));
        $this->set('activities', $activities);
*/		
		$language_ids = $this->UserLanguage->find('list',
			array('fields'=>'UserLanguage.language_id','conditions'=>array('UserLanguage.user_id'=>$this->cuid)));
		$questions = $this->Question->find('all',
			array('conditions'=>array('Question.language_id'=>$language_ids),
			'order'=>'Question.id DESC', 
			'LIMIT'=>'5'));
		$events = $this->Event->find('all',
			array('conditions'=>array(
				'Event.city_id'=>$this->current_user['User']['city_id']),
				'order'=>'Event.id DESC', 
				'LIMIT'=>5));
		$words = $this->Word->find('all', 
			array('order'=>'Word.id DESC', 
			'LIMIT'=>10));
		$jobs = $this->Job->find('all',
			array('order'=>'Job.id DESC',
			'LIMIT' => '5',
			'conditions' =>array('Job.language_id'=>$language_ids)));
		$this->set('jobs', $jobs);
		$this->set('questions', $questions);
		$this->set('events', $events);
		$this->set('words', $words);
    }

//上传头像的函数。


    function upload_avatar() {
        $upload_path = User::avatar_path . '/'; #'a_path' 格式！！记得加 /


        if (isset($this->cuid)) {
            $dst_file_name = "u_{$this->cuid}";
        } else {
            $this->Session->setFlash('something  cuid wrong!');
            $this->redirect('/login');
        }
        if (isset($_FILES['uploadfile'])) {
            $file_type = $_FILES['uploadfile']['type'];
            $file_size = $_FILES['uploadfile']['size'];
            if (!in_array($file_type, $this->Thumbnail->allow_type_list)) {
                $this->Session->setFlash('只允许上传 gif jpeg png等图片格式的文件！');
                $this->redirect('/users/upload_avatar');
            }
            if ($file_size > $this->Thumbnail->max_file_size) {
                $this->Session->setFlash('上传图片不得超过500K');
                $this->redirect('/users/upload_avatar');
            }

            $ext = end(explode('.', $_FILES['uploadfile']['name']));
            $tmp_name = time() . '_' . 'u_' . $this->cuid;
            $src_file = "tmpimgs/" . $tmp_name . '.' . $ext;
            if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $src_file)) {
                $src_img = $src_file;
                $result = $this->Thumbnail->createUserThumbs($src_img, $file_type, $dst_file_name, $upload_path);
                if ($result == true) {
                    $this->Session->setFlash('头像上传成功！');
                    $this->User->id = $this->cuid;
                    $this->User->saveField('avatar', $dst_file_name . '.jpg');
                    $this->redirect('/settings');
                } else {
                    $this->Session->setFlash($result);
                    $this->redirect('/users/upload_avatar');
                }
            } else {
                echo "Failed to upload file Contact Site admin to fix the problem";
                exit;
            }
        }
    }

    function view() {
        if (!isset($this->params['uid']) or !isset($this->uid)) {
            $this->cakeError('not_found');
        }
        $words = $this->Word->find('all', array('conditions' => array('Word.user_id' => $this->uid), 'order' => 'Word.created desc', 'limit' => 5));
        $notes = $this->Note->find('all', array('conditions' => array('Note.user_id' => $this->uid), 'order' => 'Note.created desc', 'limit' => 5));
        $guests = $this->Guest->find('all', array('conditions' => array('Guest.user_id' => $this->uid), 'order' => 'Guest.id desc', 'limit' => 5));
        $this->paginate = array(
                'limit' => 12,
                "joins" => array(array(
                                'table' => 'followships',
                                'alias' => 'Followship',
                                'conditions' => array("User.id = Followship.following_id")
                        )),
                'order' => 'Followship.id desc'
        );
        $followers_count = $this->Followship->find('count', array('conditions' => array('Followship.following_id' => $this->uid)));
        $followings = $this->paginate('User', array('Followship.user_id' => $this->uid));

        $this->set('lans', $this->UserLanguage->find('all', array('conditions' => array('UserLanguage.user_id' => $this->uid))));
        $this->set('words', $words);
        $this->set('followers_count', $followers_count);
        $this->set('followings', $followings);
        $this->set('guests', $guests);
        $this->set('user', $this->user);
        $this->set('notes', $notes);
        $languages = $this->Language->find('list');
        $this->set(compact('languages'));
    }

    function edit($id = null) {
        if (!isset($this->cuid)) {
            $this->Session->setFlash(__('Invalid user', true));
            $this->redirect(array('action' => 'index'));
        }
        if (!empty($this->data)) {
            $this->User->id = $this->cuid;
            $the_uid = $this->data['User']['uid'];
            if ($the_uid != $this->cuuid) {
                if (preg_match('/^[u][\d]+$/', $the_uid)) {
                    $this->Session->setFlash('uid不可以为u开头后面为数字的形式。');
                    $this->redirect('/settings');
                }
            }
            if ($the_uid == '') {
                $this->data['User']['uid'] = $this->cuuid;
            }
            if ($this->User->save($this->data)) {
                echo "dddddddddddddddddddddd";

                $this->Session->setFlash(__('修改用户信息成功！', true));

                $this->redirect('/settings');
            } else {
                $this->Session->setFlash(__('修改用户信息失败，请稍后再试！', true));
            }
        }
        $this->data = $this->User->read(null, $this->cuid);
    }

    function lans() {
        if (!isset($this->cuid)) {
            $this->cakeError('access');
        }
        $lans = $this->Language->find('list');
        $this->set('lans', $lans);
        $this->set('levels', $this->Level->find('list'));
        $user_lans = $this->UserLanguage->find('all', array(
                'conditions' => array('UserLanguage.user_id' => $this->cuid)
        ));
        $this->set('user_lans', $user_lans);
    }

    function delete($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for user', true));
            $this->redirect(array('action' => 'index'));
        }
        if ($this->User->delete($id)) {
            $this->Session->setFlash(__('User deleted', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('User was not deleted', true));
        $this->redirect(array('action' => 'index'));
    }

    function sendMails() {

        $this->Email->to = '<75166824@qq.com>';
        $this->Email->subject = 'Test';
        $this->Email->send('徐超，长寿路，速度！长寿路！!');
        $this->set('smtp_errors', $this->Email->smtpError);
    }

    public function _sendMail($id) {
        $user = $this->User->find($id);


        $this->Email->to = $user['User']['email'];
        $is_done = $this->Email->send();
        $this->set('smtp_errors', $this->Email->smtpError);
        return $is_done;
    }

////////////////////////////////////////////////////////////
    function admin_index()
    {
        
    }
    
    function admin_login()
    {
    	 if($this->Auth->user()) {
                $this->redirect(array('controller'=>'users', 'action'=>'admin_index'));
            }
    }

}

?>